<template>
  <el-dialog v-model="visible" title="账户提现" width="500px">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="提现金额" prop="amount">
        <el-input-number 
          v-model="form.amount" 
          :min="0.01" 
          :max="availableBalance > 0 ? availableBalance : undefined" 
          :step="100" 
          :precision="2" 
          placeholder="请输入提现金额"
          style="width: 100%"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="提现到" prop="bankCardId">
        <el-select v-model="form.bankCardId" placeholder="请选择银行卡" style="width: 100%">
          <el-option 
            v-for="card in bankCards" 
            :key="card.id" 
            :label="`${card.bankName} (${formatCardNumber(card.cardNumber)})`" 
            :value="card.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付密码" prop="password">
        <el-input v-model="form.password" show-password placeholder="请输入支付密码"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">确认提现</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { withdrawAccount } from '@/api/account';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  },
  bankCards: {
    type: Array,
    default: () => []
  },
  availableBalance: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['update:visible', 'update:loading', 'success']);

// 表单数据
const form = reactive({
  amount: 0,
  bankCardId: '',
  password: ''
});

// 表单验证规则
const rules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '提现金额必须大于0', trigger: 'blur' }
  ],
  bankCardId: [
    { required: true, message: '请选择银行卡', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, message: '支付密码长度不能小于6位', trigger: 'blur' }
  ]
};

const formRef = ref(null);

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置表单
    form.amount = 0;
    form.bankCardId = '';
    form.password = '';
    
    // 如果有默认银行卡，自动选择
    const defaultCard = props.bankCards.find(card => card.isDefault === 1);
    if (defaultCard) {
      form.bankCardId = defaultCard.id;
    }
  }
});

// 格式化银行卡号
const formatCardNumber = (cardNumber) => {
  if (!cardNumber) return '';
  
  // 将卡号格式化为 **** **** **** 1234 格式
  const lastFour = cardNumber.slice(-4);
  return `**** **** **** ${lastFour}`;
};

// 取消按钮点击
const handleCancel = () => {
  emit('update:visible', false);
};

// 确认按钮点击
const handleConfirm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      emit('update:loading', true);
      
      try {
        const response = await withdrawAccount({
          amount: form.amount,
          bankCardId: form.bankCardId,
          password: form.password
        });
        
        if (response.code === 0) {
          ElMessage.success('提现申请已提交，请等待处理');
          emit('update:visible', false);
          emit('success');
        }
      } catch (error) {
        console.error('提现失败:', error);
        ElMessage.error('提现失败，请重试');
      } finally {
        emit('update:loading', false);
      }
    }
  });
};
</script>
